import React, { useState } from 'react';
import _ from 'lodash';
import { nanoid as getNanoid } from 'nanoid';
import HeaderTitle from './components/headerTitle';
import DropViewer from './components/dropViewer';
import styles from './index.less';

export default () => {
  const [dataList, setDataList] = useState([]);

  const handleDrop = (opts) => {
    const { dragItem, nanoid } = opts;
    const generateChildGroupWithLoop = (list, nanoid, dragItem) => {
      for (let i = 0; i < list.length; i++) {
        if (list[i].nanoid === nanoid) {
          const { nanoid, children, ...restOpts } = list[i];
          if (children && children.length) {
            list[i] = {
              nanoid,
              children: _.concat(children, [
                _.assign({ nanoid: getNanoid(12) }, dragItem),
              ]),
            };
          } else {
            list[i] = {
              nanoid: getNanoid(12),
              children: [
                { nanoid, ...restOpts },
                _.assign({ nanoid: getNanoid(12) }, dragItem),
              ],
            };
          }
          return;
        } else if (list[i].children && list[i].children.length) {
          generateChildGroupWithLoop(list[i].children, nanoid, dragItem);
        }
      }
    };

    setDataList((prevList) => {
      const nextList = _.cloneDeep(prevList);
      if (nanoid) {
        generateChildGroupWithLoop(nextList, nanoid, dragItem);
      } else {
        nextList.push(_.assign({ nanoid: getNanoid(12) }, dragItem));
      }
      return nextList;
    });
  };

  const handleDelete = (nanoid) => {
    const deleteChildFromGroupWithLoop = (list, nanoid) => {
      for (let i = 0; i < list.length; i++) {
        if (list[i].children) {
          const index = _.findIndex(
            list[i].children,
            ({ nanoid: currentNanoid }) => currentNanoid === nanoid,
          );
          if (index > -1) {
            list[i].children.splice(index, 1);
            if (list[i].children.length === 1) {
              list[i] = list[i].children[0];
            }
            return;
          }
          deleteChildFromGroupWithLoop(list[i].children, nanoid);
        } else if (list[i].nanoid === nanoid) {
          list.splice(i, 1);
          return;
        }
      }
    };
    setDataList((prevList) => {
      const nextList = _.cloneDeep(prevList);
      deleteChildFromGroupWithLoop(nextList, nanoid);
      return nextList;
    });
  };

  return (
    <div className={styles.viewBox}>
      <HeaderTitle />
      <DropViewer
        dataList={dataList}
        onDrop={handleDrop}
        handleDelete={handleDelete}
      />
    </div>
  );
};
